<template>
  <div style="margin:100px 0">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />

    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>

import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { importEmployee } from '@/api/employees'
import { formatExcelDate } from '@/utils/index.js'
import dayjs from 'dayjs'

export default {
  name: 'VueAdminTemplateMasterImport',
  components: {
    UploadExcelComponent
  },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },

  mounted() {

  },

  methods: {
    // 数据转换抽离封装
    transData(arr, Info, whiteList) {
      const newArr = arr.map(item => {
        const newObj = {}
        const zhKey = Object.keys(item)
        zhKey.forEach(key => {
          if (whiteList.includes(Info[key])) {
            newObj[Info[key]] = dayjs(new Date(formatExcelDate(item[key]))).format('YYYY-MM-DD')
          } else {
            newObj[Info[key]] = item[key]
          }
        })
        return newObj
      })
      return newArr
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async handleSuccess({ results, header }) {
      // console.log(results)

      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      // console.log(this.transData(results, mapInfo))
      const whiteList = ['timeOfEntry', 'correctionTime']
      const val = this.transData(results, mapInfo, whiteList)
      const res = await importEmployee(val)
      // console.log(res)
      if (!res.success) return
      // console.log(val)
      this.tableData = results
      this.tableHeader = header

      // map和foreach的区别

      // forEach()方法不会返回执行结果，而是undefined。
      // 也就是说，forEach()会修改原来的数组。
      // 而map()方法会得到一个新的数组并返回。
      // const newArr = results.map(item => {
      //   const newObj = {}
      //   const zhKey = Object.keys(item)
      //   zhKey.forEach(key => {
      //     newObj[mapInfo[key]] = item[key]
      //   })
      //   return newObj
      // })
      // console.log(newArr)
    }

  }
}
</script>

<style lang="scss" scoped>

</style>
